package com.dragonwu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

/**
 * @author DragonWu
 * @since 2022-10-10 9:56
 **/
@EnableAuthorizationServer //开启授权服务器的功能
@Configuration
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    @Qualifier("userServiceDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    /*
    添加第三方的客户端
    */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("dragon-api")//第三方客户端的名称
                .secret(passwordEncoder.encode("dragon-secret"))//第三方客户端的密钥
                .scopes("all")//第三方客户端的授权范围
                .authorizedGrantTypes("password", "refresh_token")//密码模式、token刷新模式
                .accessTokenValiditySeconds(7 * 24 * 3600)//token的有效期
                .refreshTokenValiditySeconds(30 * 24 * 3600)//refresh_token的有效期
                .and()
                ///应用之间内部的访问形式
                .withClient("inside-app")
                .secret(passwordEncoder.encode("inside-secret"))
                .authorizedGrantTypes("client_credentials")//客户端授权，固定写法
                .scopes("all")
                .accessTokenValiditySeconds(7 * 24 * 3600);
        super.configure(clients);
    }

    /*
    配置验证管理器，UserDetailsService
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(jwtTokenStore()) //采用JWT存储token
                .tokenEnhancer(jwtAccessTokenConverter()); //token转换器
        super.configure(endpoints);
    }

    /*
    JWT token 存储
     */
    private TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /*
    JWT转换器
     */
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();

        //加载我们的私钥
        ClassPathResource classPathResource = new ClassPathResource("keys/dragonwu.jks");
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "dragonwu".toCharArray());//第二个参数为你生成密钥时输入的password
        tokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("dragonwu", "dragonwu".toCharArray()));//第一个参数是生成密钥是的alias,第二个是password

        return tokenConverter;
    }
}
